﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using HZYProject.Service.ExamServices;
using HZYProject.Service.ResultServices;
using HZYProject.Service.StudentServices;
using HZYProject.Web.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZYProject.Web.Controllers
{
    /// <summary>
    /// 考试管理
    /// </summary>
    [Route("Exam")]
    public class ExamController : Controller
    {
        private readonly IRepository<Exam, Guid> _repository;
        private readonly IRepository<Course, Guid> _courseRepository;
        private readonly IRepository<TestPaper, Guid> _testPaperRepository;
        private readonly IExamService _examService;
        private readonly IStudentService _studentService;
        private readonly IRepository<Colleges, Guid> _collegesRepository;
        private readonly IRepository<Result, Guid> _resultRepository;
        private readonly IResultService _resultService;

        public ExamController(IResultService resultService, IRepository<Result, Guid> resultRepository, IRepository<Colleges, Guid> collegesRepository, IStudentService studentService, IRepository<Exam, Guid> repository, IRepository<Course, Guid> courseRepository, IExamService examService, IRepository<TestPaper, Guid> testPaperRepository)
        {
            _repository = repository;
            _courseRepository = courseRepository;
            _examService = examService;
            _testPaperRepository = testPaperRepository;
            _studentService = studentService;
            _collegesRepository = collegesRepository;
            _resultRepository = resultRepository;
            _resultService = resultService;
        }

        #region 首页分页查询
        [HttpGet("")]
        public IActionResult Index()
        {
            var list = _courseRepository.GetAllList();
            ViewBag.Names = _testPaperRepository.GetAllList();
            return View(list);
        }
        [HttpPost("")]
        public async Task<IActionResult> Index(UIExam e)
        {
            try
            {
                GetExamInput input = new GetExamInput { ID = e.ExamID, Title = e.Title, CID = e.CourseID, TID = e.TestPaperID };
                var data = await _examService.GetPaginatedResult(input);
                var list = data.Data.Select(x => new UIExam
                {
                    ExamID = x.ExamID,
                    Title = x.Title,
                    CourseID = x.CourseID,
                    CreateTime = x.CreateTime,
                    Duration = x.Duration,
                    StartTime = x.StartTime,
                    TestPaperID = x.TestPaperID,
                    CourseName = x.Course.Title,
                    TestPaperTitle = x.TestPaper.Title,
                    StuNumber = x.Results.Where(p => x.ExamID == p.ExamID).Count()
                });
                return Json(new { code = 0, msg = "", data = list, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UIExam>(), count = 0 });
            }
        }
        #endregion

        #region 添加
        [HttpGet("add")]
        public IActionResult Add()
        {
            var list = _courseRepository.GetAllList();
            ViewBag.Names = _testPaperRepository.GetAllList();
            return View(list);
        }
        [HttpPost("add")]
        public IActionResult Add(UIExam exam)
        {
            try
            {
                Exam e = new Exam();
                e.ExamID = Guid.NewGuid();
                e.Title = exam.Title;
                e.CourseID = exam.CourseID;
                e.TestPaperID = exam.TestPaperID;
                e.Duration = exam.Duration;
                e.StartTime = exam.StartTime;
                e.CreateTime = DateTime.Now;
                _repository.Insert(e);
                return Json(new { success = true, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 修改
        [HttpGet("edit")]
        public IActionResult Edit(Guid id)
        {
            var obj = _repository.FirstOrDefault(x => x.ExamID == id);
            ViewBag.Course = _courseRepository.GetAllList();
            ViewBag.TestPaper = _testPaperRepository.GetAllList();
            return View(obj);
        }
        [HttpPost("edit")]
        public IActionResult Edit(UIExam exam)
        {
            try
            {
                if (ModelState.IsValid)//obj在形成对象时，是否全部符合注解中的规定
                {
                    var obj = _repository.FirstOrDefault(x => x.ExamID == exam.ExamID);
                    obj.Title = exam.Title;
                    obj.CourseID = exam.CourseID;
                    obj.TestPaperID = exam.TestPaperID;
                    obj.Duration = exam.Duration;
                    obj.StartTime = exam.StartTime;
                    _repository.Update(obj);
                    return Json(new { success = true, msg = "修改成功" });
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var v in ModelState.Values)
                    {
                        foreach (var p in v.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new { success = false, msg = "服务端验证未通过," + sb });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }

        }
        #endregion

        #region 删除
        [HttpPost("remove/{id}")]
        public IActionResult Del(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.ExamID == id);
                _repository.Delete(obj);
                return Json(new { success = true, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 查找考试人员
        [HttpGet("setStu")]
        public IActionResult SetStu(Guid id)
        {
            var list = _repository.FirstOrDefault(x => x.ExamID == id);
            ViewBag.Names = _collegesRepository.GetAllList();
            return View(list);
        }
        [HttpPost("setStu")]
        public async Task<IActionResult> SetStu(UIStudent stu)
        {
            try
            {
                GetStudentInput input = new GetStudentInput { ID = stu.StudentID, Name = stu.RealName, CID = stu.CollegesId };
                var data = await _studentService.GetPaginatedResult(input);
                var list = data.Data.Select(x => new UIStudent
                {
                    StudentID = x.StudentID,
                    WXOpenID = x.WXOpenID,
                    IdNo = x.IdNo,
                    PassWord = x.PassWord,
                    CollegesId = x.CollegesId,
                    RealName = x.RealName,
                    Sex = x.Sex,
                    Mphone = x.Mphone,
                    Email = x.Email,
                    CreateTime = x.CreateTime,
                    Status = x.Status,
                    CollegeName = x.Colleges.Name
                });
                return Json(new { code = 0, msg = "", data = list, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UIStudent>(), count = 0 });
            }
        }
        #endregion

        #region 添加考试人员
        [HttpPost("addStu")]
        public IActionResult AddStu(string ids, Guid eid)
        {
            try
            {
                //var list = _resultRepository.GetAll().Where(x => x.ExamID == eid).ToList();
                //var str = "";
                //for (int i = 0; i < list.Count; i++)
                //{
                //    str += list[i].StudentID + ",";
                //}
                //str = str.Substring(0, str.Length - 1);

                //if (ids.Contains(str))
                //{

                //}
                //else
                //{

                //}
                var stus = ids.Split(",");
                foreach (var item in stus)
                {
                    Result r = new Result();
                    r.ScoreID = new Guid();
                    r.ExamID = eid;
                    r.StudentID = new Guid(item);
                    r.Score = 0;
                    _resultRepository.Insert(r);
                }
                return Json(new { success = true, msg = "加入成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 查看考试人员
        [HttpGet("examPerson")]
        public IActionResult ExamPerson(Guid id)
        {
            var list = _repository.FirstOrDefault(x => x.ExamID == id);
            return View(list);
        }
        [HttpPost("examPerson")]
        public async Task<IActionResult> ExamPerson(UIResult r)
        {
            try
            {
                GetResultInput input = new GetResultInput { ID = r.ScoreID, EID = r.ExamID };
                var data = await _resultService.GetPaginatedResult(input);
                var list = data.Data.Select(x => new UIResult
                {
                    ScoreID = x.ScoreID,
                    StudentID = x.StudentID,
                    ExamID = x.ExamID,
                    Score = x.Score,
                    RealName = x.Student.RealName,
                    IdNo = x.Student.IdNo
                });
                return Json(new { code = 0, msg = "", data = list, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UIResult>(), count = 0 });
            }
        }
        #endregion

        #region 重置考试人员
        [HttpPost("resetStu/{id}")]
        public IActionResult ResetStu(Guid id)
        {
            try
            {
                var obj = _resultRepository.FirstOrDefault(x => x.ScoreID == id);
                obj.Score = 0;
                _resultRepository.Update(obj);
                return Json(new { success = true, msg = "重置成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }

        }
        #endregion

        #region 删除考试人员
        [HttpPost("removeStu/{id}")]
        public IActionResult RemoveStu(Guid id)
        {
            try
            {
                var obj = _resultRepository.FirstOrDefault(x => x.ScoreID == id);
                _resultRepository.Delete(obj);
                return Json(new { success = true, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 批量删除考试人员
        [HttpPost("batchDeleteStu")]
        public IActionResult BatchDeleteStu(string ids)
        {
            try
            {
                var str = ids.Split(",");
                foreach (var item in str)
                {
                    Guid id = new Guid(item);
                    var obj = _resultRepository.FirstOrDefault(x => x.ScoreID == id);
                    _resultRepository.Delete(obj);
                }
                return Json(new { success = true, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

    }
}
